import wxValidate from 'wechat-validate'
Page({
  data: {
    countDownVisible: false,
    timeData: {},
    mobile: '15645568965',
    code: '',
  },
  behaviors: [wxValidate],
  rules: {
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!' },
    ],
    code: [
      { required: true, message: '请填写验证码!' },
      { pattern: /^\d{6}$/, message: '请填写正确的验证码!' },
    ],
  },
  //获取短信验证码
  async handCountDown() {
    const { valid, message } = this.validate('mobile')
    // 如果验证不合法则不再执行后面的逻辑
    if (!valid) return wx.utils.toast(message)
    this.setData({
      countDownVisible: true,
    })
    const res = await wx.http.get('/code', { mobile: this.data.mobile })
    this.setData({
      code: res.data.data.code,
    })
  },
  async login() {
    if (!this.validate()) return
    const res = await wx.http.post('/login', {
      mobile: this.data.mobile,
      code: this.data.code,
    })
    const app = getApp()
    app.setToken(res.data.data.token)
    app.setRefreshToken(res.data.data.refreshToken)

    let { returnType, returnUrl } = this.options
    
    if (!returnUrl) {
      returnUrl = '/pages/index/index'
      // eslint-disable-next-line no-unused-vars
      returnType = 'switchTab'
    }
    if (returnUrl && !returnType) {
      returnType = 'redirectTo'
    }

    wx[returnType]({
      url: returnUrl,
  })
    // wx[this.options.returnType || 'redirectTo']({
    //   url: this.options.returnUrl,
    // })
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
})
